<?php

namespace App\Http\Controllers\AgentAdmin;

use App\Enums\AssetSourceType;
use App\Exports\AssetGiveExport;
use App\Jobs\DownloadsJob;
use App\Models\AgentUser;
use App\Models\Asset;
use App\Models\Download;
use App\Models\Product;
use Carbon\Carbon;
use Vinlon\Laravel\LayAdmin\PaginateResponse;

class AssetController
{
    /**
     * 资产转赠记录.
     */
    public function giveRecords(): PaginateResponse
    {
        /** @var AgentUser $user */
        $user = auth()->user();

        $query = Asset::query()
            ->select('assets.*')
            ->leftJoin('frontend_users', 'frontend_users.id', 'assets.user_id')
            ->where('frontend_users.agent_id', $user->agent_id)
            ->where('source_type', AssetSourceType::GIVE)
            ->when(request()->keyword, function ($q) {
                $likeVal = '%' . request()->keyword . '%';
                $addresses = Product::query()->where('name', 'like', $likeVal)->pluck('contract_address');

                return $q->whereIn('contract_address', $addresses);
            })
            ->when(request()->start_date, function ($q) {
                return $q->where('assets.created_at', '>=', Carbon::parse(request()->start_date)->startOfDay());
            })
            ->when(request()->end_date, function ($q) {
                return $q->where('assets.created_at', '<=', Carbon::parse(request()->end_date)->endOfDay());
            })
            ->orderByDesc('assets.id')
            ->with(['user', 'product', 'giveUser'])
        ;

        return paginate_result($query);
    }

    public function giveRecordsExport()
    {
        /** @var AgentUser $user */
        $user = auth()->user();

        $file = '转赠记录' . date('YmdHis') . uniqid() . '.xls';

        $download = Download::create([
            'agent_id' => $user->agent_id,
            'user_id' => $user->id,
            'name' => $file,
            'url' => 'storage/' . $file,
            'status' => 0,
            'model' => AssetGiveExport::class,
            'request' => json_encode(request()->all()),
        ]);

        dispatch(new DownloadsJob($download));
    }
}
